//
//  NewFriendTableViewController.m
//  IMChat
//
//  Created by Admin on 2021/7/2.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "NewFriendTableViewController.h"

@interface NewFriendTableViewController ()

//搜索框
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;

//section标题数组
@property (nonatomic, strong) NSArray *sectionTitle;

//好友信息请求对象数组
@property (strong, nonatomic) NSMutableArray<RCContactNotificationMessage *> *nFriendReqList;

//好友信息对象数组
@property (strong, nonatomic) NSMutableArray<FriendInfoModel *> *friendModelList;

@end


@implementation NewFriendTableViewController

//将要布局子视图
-(void)viewWillLayoutSubviews{
    
}

//已经布局子视图
-(void)viewWillAppear:(BOOL)animated{
    //刷新cell
    [self initData];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _sectionTitle = @[@"好友申请"];
    
    //添加搜索栏
    _searchBar = [[UISearchBar alloc]
                           initWithFrame:CGRectMake(0, 0, self.view.intrinsicContentSize.width, 44)];
    _searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //search.barTintColor = [UIColor colorWithRed:0.502 green:0.502 blue:1 alpha:1.00];
    _searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.tableView.tableHeaderView = _searchBar;
    
    _searchBar.placeholder = @"请输入要添加的好友ID";
    //search.showsScopeBar = NO;
    _searchBar.showsCancelButton = YES;
    [self searchBarTextDidBeginEditing:_searchBar];
    
    [self initData];
    
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([TONewFridMsgTableViewCell class]) bundle:nil];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerNib:nib forCellReuseIdentifier:@"newFriendMsgCell"];

}

#pragma mark 加载数据
-(void)initData{
    /** 获得全局变量. */
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    _nFriendReqList = myDelegate.nFriendReqList;
}

//改变concel的显示和方法
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * addFriend =(UIButton *)view;
            [addFriend setTitle:@"添加" forState:UIControlStateNormal];
            addFriend.titleLabel.font = [UIFont systemFontOfSize:16];
            [addFriend addTarget:self action:@selector(addNewFriend) forControlEvents:UIControlEventTouchDown];
        }
    }
}

// 添加新好友，对别人发送请求
- (void)addNewFriend{
    NSLog(@"%@",_searchBar.text);
    
    /** 获得全局变量. */
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    RCContactNotificationMessage *addFriendMessage = [[RCContactNotificationMessage alloc]init];
    addFriendMessage.operation = @"Request";
    addFriendMessage.sourceUserId = myDelegate.userId;
    addFriendMessage.targetUserId = _searchBar.text;
    addFriendMessage.message = @"你好，可以加个好友吗？";
    
    [TOAFHttpUtils findUserIsExist:_searchBar.text
        withBlock:^(NSString *result) {
            NSLog(@"%@",result);
            if([result isEqualToString:@"success"]){
                
                [TOAFHttpUtils sendAddNewFriendMessage:addFriendMessage withBlock:^(NSString * _Nonnull result) {
                    if([result isEqualToString:@"success"]){
                        // 获取主线程队列
                        dispatch_async(dispatch_get_main_queue(),^{
                            // 发送成功弹窗
                            [self alertTool:@"发送成功！"];
                        });
                        //添加好友请求数据信息
                        [TOAFHttpUtils addNewFriendRequestInfo:addFriendMessage];
                    }
                    else{
                        // 获取主线程队列
                        dispatch_async(dispatch_get_main_queue(),^{
                            // 发送成功弹窗
                            [self alertTool:@"发送失败！"];
                        });
                    }
                }];
                
            }else if([result isEqualToString:@"error-1000"]){
                [self alertTool:@"用户不存在！！"];
            }else{
                NSLog(@"未知错误！");
            }
    }];
    
}

#pragma mark - Table view data source

// 返回分区数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return [_sectionTitle count];
}

// 返回分区的title（分区是从 0 开始的）
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    // 根据分区的获取对应的名称
    return _sectionTitle[section];//返回分区中的内容
}

//返回对应section(indexPath)有多少元素(行数)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    // 根据分区，获取分区中对应要显示的数据长度
    if(section == 0){
        return [_nFriendReqList count];//返回数组对象中的数量
    }else{
        return 0;
    }
}

//设置并返回每一个cell，可以在这里对cell进行个性化的设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TONewFridMsgTableViewCell *cell = (TONewFridMsgTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"newFriendMsgCell"];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TONewFridMsgTableViewCell" owner:self options:nil] lastObject];
    }
    
    // 根据分区设置UITableViewCell显示的数据
    if(indexPath.section == 0){
        RCContactNotificationMessage *nFReq = [[RCContactNotificationMessage alloc]init];
        nFReq = _nFriendReqList[indexPath.row];
        
        NSString *operation = nFReq.operation;
        
        cell.friendName.text = nFReq.sourceUserId;
        cell.detailLabel.text = nFReq.message;
        cell.imageView.image = [UIImage imageNamed:@"touxiang3"];
        //调整图片大小
        CGSize itemSize = CGSizeMake(38, 38);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [cell.imageView.image drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        if([operation isEqualToString:@"Request"]){
            [cell.sureBtn addTarget:self action:@selector(acceptNFRequest:) forControlEvents:UIControlEventTouchDown];
            cell.sureBtn.tag = indexPath.row;
        }
        
        if([operation isEqualToString:@"AcceptResponse"]){
            [cell.sureBtn setTitle:@"已添加" forState:UIControlStateNormal];
            cell.sureBtn.enabled = NO;
            cell.sureBtn.tintColor = [UIColor colorWithRed:41/255 green:36/255 blue:33/255 alpha:1.00];
            cell.sureBtn.tag = indexPath.row;
        }
        
        if([operation isEqualToString:@"RejectResponse"]){
            [cell.sureBtn setTitle:@"已拒绝" forState:UIControlStateNormal];
            cell.sureBtn.enabled = NO;
            cell.sureBtn.tintColor = [UIColor colorWithRed:41/255 green:36/255 blue:33/255 alpha:1.00];
            cell.sureBtn.tag = indexPath.row;
        }
    }
    
    // 返回设置好数据的cell给UITableView对象
    return cell;
}

-(void)acceptNFRequest:(UIButton *)button{
    
    NSLog(@"点击的是第%ld行按钮",button.tag);
    
    RCContactNotificationMessage *nFReq = [[RCContactNotificationMessage alloc]init];
    nFReq = _nFriendReqList[button.tag];
    
    /** 获得全局变量. */
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    RCInformationNotificationMessage *txMsg = [RCInformationNotificationMessage notificationWithMessage:@"你们已经是好友了，快来聊天吧！" extra:nil];
    
    RCContactNotificationMessage *acceptMsg = [RCContactNotificationMessage
           notificationWithOperation:@"AcceptResponse"
                        sourceUserId:nFReq.sourceUserId
                        targetUserId:myDelegate.userId
                             message:nil
                               extra:nil];
    
    //轻服务添加好友关系
    [TOAFHttpUtils acceptAddNewFriend:myDelegate.userId
                         withFriendId:nFReq.sourceUserId
        withBlock:^(NSString * _Nonnull result) {
            if([result isEqualToString:@"success"]){
                NSLog(@"添加成功！");
                [[RCIM sharedRCIM]
                 sendMessage:ConversationType_PRIVATE
                 targetId:nFReq.sourceUserId
                 content:txMsg
                 pushContent:nil pushData:nil
                 success:^(long messageId) {
                     NSLog(@"发送成功");
                     // 获取主线程队列
                     dispatch_async(dispatch_get_main_queue(),^{
                         // 发送成功弹窗
                         [self alertTool:@"添加成功！"];
                         [button setTitle:@"已添加" forState:UIControlStateNormal];
                         button.enabled = NO;
                         button.tintColor = [UIColor colorWithRed:41/255 green:36/255 blue:33/255 alpha:1.00];
                     });
                     //更新好友列表数据
                     [TOAFHttpUtils findUserFriends:myDelegate.userId withBlock:^(NSString * _Nonnull result) {
                         NSLog(@"%@",result);
                     }];
                     
                     // 更新轻服务好友请求的operation信息
                     [TOAFHttpUtils updateAcceptRequest:acceptMsg];
                     
                     // 重新查询用户好友请求信息表
                     [TOAFHttpUtils findNewFiendRequestInfo:myDelegate.userId];
                     
                 }error:^(RCErrorCode nErrorCode, long messageId) {
                     NSLog(@"发送失败");
                     // 获取主线程队列
                     dispatch_async(dispatch_get_main_queue(),^{
                         // 发送失败弹窗
                         [self alertTool:@"添加失败！"];
                     });
                 }];
            }
         }];
    
    
}

// 选中了cell时触发
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(indexPath.section == 0){
//        
//        // 隐藏底部tarbar
//        self.tabBarController.tabBar.hidden = YES;
//        
//        //[self.navigationController pushViewController:conversationVC animated:YES];
//    }
}

//设置每个cell的高度（通用的方法）
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:
(NSIndexPath *)indexPath{
    
    return 50.0f;
}

//设置header seaction的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40.0f;
}

//设置footer seaction的高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 20.0f;
}

// 弹窗工具
- (void)alertTool:(NSString *)message{
    //先创建一个弹窗控制器 然后里面有title和message来提示需要的东西
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加一个弹窗的action 活动可以是取消 可以是确认
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:NO completion:nil];
}


@end
